<script setup lang="ts">

import { onMounted, reactive, ref } from 'vue'
import type { PageInfo, Result } from '@/tools/request'
import { Message, Modal } from '@arco-design/web-vue'
import type { SysMenu } from '@/api/system/sysMenu/sysMenu.d'
import {
  sysMenuAdd,
  sysMenuById, sysMenuList,
  sysMenuModify,
  sysMenuRemove, sysMenuRemoveBatch
} from '@/api/system/sysMenu/sysMenu'
import { useGlobalStore } from '@/stores/global'

//表单部分
const sysMenuFormRef = ref()
const sysMenuForm = reactive({
  //搜索表单
  query: {} as SysMenu,
  submitQuery: () => {
    sysMenuList(sysMenuForm.query, {
      pageNum: sysMenuTable.pageInfo.pageNum | 0,
      pageSize: 99999
      //@ts-ignore
    }).then((resp: Result<PageInfo<SysMenu>>) => {
        const list = resp.data.list
        const map = new Map()
        list.forEach(v => {
          map.set(v.id, v)
        })
        list.forEach(v => {
          if (v.parentId) {
            if (!(map.get(v.parentId)['children'])) {
              map.get(v.parentId)['children'] = []
            }
            map.get(v.parentId)['children'].push(v)
          }
        })
        resp.data.list = []
        map.forEach((value: SysMenu) => {
          if (!value.parentId) {
            resp.data.list.push(value)
          }
        })
        sysMenuTable.pageInfo = resp.data
      }
    )
  },
  //新增修改表单
  form: {
    id: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    delBy: null,
    del: null,
    remark: null,
    menuName: null,
    isSubMenu: null,
    icon: null,
    parentId: null,
    url: null,
    componentPath: null,
    weight: null,
    isHidden: false
  } as SysMenu,
  submitForm: ({ values, errors }: any) => {
    if (errors) return
    //修改
    if (sysMenuForm.form.id) {
      sysMenuModify(sysMenuForm.form).then(() => {
        Message.success('修改系统菜单成功')
        sysMenuForm.visible = false
        sysMenuForm.submitQuery()
      })
      return
    }
    //新增
    sysMenuAdd(sysMenuForm.form).then(() => {
      Message.success('新建系统菜单成功')
      sysMenuForm.visible = false
      sysMenuForm.submitQuery()
    })
  },
  //弹出层title
  formTitle: '新增系统菜单',
  //是否显示新增修改表单
  visible: false
})

const sysMenuTable = reactive({
  pageInfo: {} as PageInfo<SysMenu>,
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  getList: (current: number) => {
    sysMenuList(sysMenuForm.query, {
      pageNum: current,
      pageSize: sysMenuTable.pageInfo.pageSize
      //@ts-ignore
    }).then((resp: Result<PageInfo<SysMenuTable>>) => {
      sysMenuTable.pageInfo = resp.data
    })
  },
  selectKeys: [] as string[],
  batchDelete: () => {
    Modal.confirm({
      title: '警告',
      content: `确认删除系统菜单【${sysMenuTable.selectKeys}】吗？`,
      onOk(e) {
        sysMenuRemoveBatch(sysMenuTable.selectKeys!).then(() => {
          Message.success(`批量删除系统菜单成功`)
          sysMenuForm.submitQuery()
        })
      }
    })
  },
  add: () => {
    //新增系统菜单
    sysMenuFormRef.value!.resetFields()
    sysMenuForm.formTitle = '新增系统菜单'
    sysMenuForm.visible = true
    sysMenuForm.form.id = null
  },
  edit: (sysMenu: SysMenu) => {
    //编辑系统菜单
    sysMenuFormRef.value!.resetFields()
    sysMenuForm.formTitle = '修改系统菜单'
    sysMenuForm.visible = true
    //@ts-ignore
    sysMenuById(sysMenu.id!).then((resp: Result<SysMenu>) => {
      sysMenuForm.form = resp.data
    })
  },
  delete: (sysMenu: SysMenu) => {
    //删除系统菜单
    Modal.confirm({
      title: '警告！',
      content: `确认删除系统菜单【${sysMenu.id}】吗？`,
      onOk(e) {
        sysMenuRemove(sysMenu.id!).then(() => {
          Message.success(`删除系统菜单【${sysMenu.id}】成功`)
          sysMenuForm.submitQuery()
        })
      }
    })
  }
})

onMounted(() => {
  sysMenuForm.submitQuery()
})

const globalStore = useGlobalStore()
</script>

<template>
  <a-breadcrumb class="my-3">
    <a-breadcrumb-item>系统管理</a-breadcrumb-item>
    <a-breadcrumb-item>菜单管理</a-breadcrumb-item>
  </a-breadcrumb>
  <a-layout-content>
    <a-card>
      <template #title>
        菜单管理
      </template>

      <a-space class="my-3">
        <a-button v-permission="'permission:sysMenu:create'" type="primary" @click="sysMenuTable.add">
          <template #icon>
            <IconPlus />
          </template>
          新建
        </a-button>
        <a-button v-permission="'permission:sysMenu:batchDelete'" class="removeBtn" @click="sysMenuTable.batchDelete">
          <template #icon>
            <IconDelete />
          </template>
          批量删除
        </a-button>
        <a-button v-permission="'permission:sysMenu:list'" class="removeBtn" @click="sysMenuForm.submitQuery">
          <template #icon>
            <IconRefresh />
          </template>
          刷新
        </a-button>
      </a-space>

      <a-table row-key="id" :data="sysMenuTable.pageInfo.list"
               :row-selection="sysMenuTable.rowSelection"
               v-model:selected-keys="sysMenuTable.selectKeys" :pagination="false">
        <template #columns>
          <a-table-column data-index="id" title="ID" />
          <a-table-column data-index="weight" title="权重" />
          <a-table-column data-index="menuName" title="菜单名" />
          <a-table-column data-index="isSubMenu" title="是否为子菜单" />
          <a-table-column data-index="icon" title="图标">
            <template #cell="{record}">
              <component :is="record.icon" />
            </template>
          </a-table-column>
          <a-table-column data-index="parentId" title="上级ID" />
          <a-table-column data-index="url" title="路由地址" />
          <a-table-column data-index="componentPath" title="组件地址" />

          <a-table-column title="操作" width="200">
            <template #cell="{record}">
              <a-space>
                <a-button @click="sysMenuTable.edit(record)"
                          v-permission="'permission:sysMenu:update'"
                          type="text">
                  <template #icon>
                    <IconEdit />
                  </template>
                  编辑
                </a-button>
                <a-button @click="sysMenuTable.delete(record)" type="text"
                          v-permission="'permission:sysMenu:delete'"
                          class="text-danger">
                  <template #icon>
                    <IconDelete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <div class="d-flex justify-content-end mt-2">
        <a-pagination :total="sysMenuTable.pageInfo.total" :page-size="sysMenuTable.pageInfo.pageSize"
                      :current="sysMenuTable.pageInfo.pageNum"
                      @change="sysMenuTable.getList" class="mt-3"></a-pagination>
      </div>

      <a-modal :title="sysMenuForm.formTitle" title-align="start"
               v-model:visible="sysMenuForm.visible"
               :footer="null">
        <a-form ref="sysMenuFormRef" :model="sysMenuForm.form"
                @submit="sysMenuForm.submitForm">

          <a-form-item field="menuName" hide-asterisk label="菜单名"
                       :rules="[{ required: true,message: '菜单名不能为空！' }]"
                       validate-trigger="blur">
            <a-input v-model="sysMenuForm.form.menuName"></a-input>
          </a-form-item>
          <a-form-item>
            <a-row :gutter="20">
              <a-col :span="12">
                <a-checkbox v-model="sysMenuForm.form.isSubMenu" />
                是否为子菜单
              </a-col>
              <a-col :span="12">
                <a-checkbox v-model="sysMenuForm.form.isHidden" />
                是否隐藏菜单
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item field="icon" hide-asterisk label="图标"
                       validate-trigger="blur">
            <a-input v-model="sysMenuForm.form.icon"></a-input>
          </a-form-item>
          <a-form-item field="parentId" hide-asterisk label="上级ID"
                       validate-trigger="blur">
            <a-select v-model.number="sysMenuForm.form.parentId">
              <a-option :label="v.key" :value="!isNaN(v.value) ? Number(v.value) : v.value" :key="i" v-for="(v,i) in globalStore.cache.sysDatabaseCache.sysMenu"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="weight" hide-asterisk label="路由权重"
                       validate-trigger="blur">
            <a-input-number v-model.number="sysMenuForm.form.weight"></a-input-number>
          </a-form-item>
          <a-form-item field="url" hide-asterisk label="路由地址"
                       validate-trigger="blur">
            <a-input v-model="sysMenuForm.form.url"></a-input>
          </a-form-item>
          <a-form-item field="componentPath" hide-asterisk label="组件地址"
                       validate-trigger="blur">
            <a-input v-model="sysMenuForm.form.componentPath"></a-input>
          </a-form-item>
          <a-form-item field="remark" hide-asterisk label="备注"
                       validate-trigger="blur">
            <a-input v-model="sysMenuForm.form.remark"></a-input>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </a-layout-content>
</template>

<style scoped lang="scss">
</style>
